package cnu.ldc.jdbctest;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cnu.ldc.util.DBconnection;
import cnu.ldc.util.ResultSetHandler;

public class JdbcTemplate {
public static int update(String sql,Object...param) {
	int rownum=0;
	Connection con=DBconnection.getConnection();
	PreparedStatement pst;
	try {
		pst = con.prepareStatement(sql);
		ParameterMetaData pmd=pst.getParameterMetaData();
		if(null!=param&&param.length!=0&pmd.getParameterCount()==param.length) {
			for(int i=0,len=param.length;i<len;i++) {
				pst.setObject(i+1, param[i]);
			}
		}
		rownum=pst.executeUpdate();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return rownum;
}
public static <T> T query(String sql,ResultSetHandler<T> rsh,Object...param) {
	T t=null;
	Connection con=DBconnection.getConnection();
	PreparedStatement pst;
	try {
		pst = con.prepareStatement(sql);
		ParameterMetaData pmd=pst.getParameterMetaData();
		if(null!=param&&param.length!=0&pmd.getParameterCount()==param.length) {
			for(int i=0,len=param.length;i<len;i++) {
				pst.setObject(i+1, param[i]);
			}
		}
		ResultSet rs=pst.executeQuery();
		t=rsh.handler(rs);
	
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DBconnection.close(con);
	}
	return t;
}
}
